package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.UserApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.WalletAPiImp;
import com.cuckoo.cuckoo_app2.apiAsync.UserApi;
import com.cuckoo.cuckoo_app2.apiAsync.WalletApi;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.WalletaMnagement;
import com.cuckoo.cuckoo_app2.dao.WithdrawalInformation;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Objects;


public class WithdraAcitity extends AppCompatActivity {

    private Context context;
    private ViewHolder holder;
    private String radioValue;
    private WalletApi walletApi;
    private UserApi userApi;
    private WalletaMnagement walletaMnagement;
    private WithdrawalInformation withdrawalInformation;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal);
        this.context = this;
        this.holder = new ViewHolder();
        this.walletApi = new WalletAPiImp();
        this.userApi = new UserApiImp();

        holder.radioAlipay.setChecked(true);
        radioValue = "alipay";

        // 隐藏微信
        holder.radioWechat.setVisibility(View.GONE);

        // 获取我的钱包
        getWallet();
        // 获取我的提现信息
        getWithdrawalInformation();

        // 绑定按钮事件
        holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.d("TEST", "checkedId: " + checkedId);
                // checkedId 是选中项的id
                if (checkedId == R.id.radioAlipay) {
                    radioValue = "alipay";
                } else if (checkedId == R.id.radioWechat) {
                    radioValue = "wechat";
                }
            }
        });

        // 绑定提交事件
        holder.et_submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                submitWithdraw();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 获取钱包信息
     */
    public void getWallet() {
        User user = MyApplication.instances.getUser();
        walletApi.performGetWalletAsync(user.getId(), new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                // 视图
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    walletaMnagement = gson.fromJson(result, WalletaMnagement.class);

                    // 渲染页面
                    holder.tv_withdraw_balance.setText(walletaMnagement.getBalance().toString());
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                runOnUiThread(() -> {
                    DialogUtils.showToast(context, errorMessage);
                });
            }
        });
    }

    /**
     * 获取我的提现信息
     */
    public void getWithdrawalInformation() {
        userApi.performGetWithdrawalInformationAsync(radioValue, new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                    withdrawalInformation = gson.fromJson(result, WithdrawalInformation.class);
                    if (withdrawalInformation.getType().equals("alipay")) {
                        holder.et_account.setText(withdrawalInformation.getAccount());
                        holder.et_name.setText(withdrawalInformation.getName());
                        holder.et_phone.setText(withdrawalInformation.getPhone());
                    }
                });
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });
    }

    /**
     * 提交提现
     */
    public void submitWithdraw() {
        String account = holder.et_account.getText().toString();
        String name = holder.et_name.getText().toString();
        String phone = holder.et_phone.getText().toString();
        String withdraw = holder.et_withdraw.getText().toString();

        if (withdrawalInformation == null) {
            withdrawalInformation = new WithdrawalInformation();
        }

        withdrawalInformation.setAccount(account);
        withdrawalInformation.setName(name);
        withdrawalInformation.setPhone(phone);
        withdrawalInformation.setType(radioValue);

        if (withdrawalInformation.getAccount().isEmpty()) {
            DialogUtils.showToast(context, "请输入提现账号");
            return;
        }
        if (withdrawalInformation.getName().isEmpty()) {
            DialogUtils.showToast(context, "请输入提现姓名");
            return;
        }
        if (withdrawalInformation.getPhone().isEmpty()) {
            DialogUtils.showToast(context, "请输入提现手机号");
            return;
        }
        if (withdraw.isEmpty()) {
            DialogUtils.showToast(context, "请输入提现金额");
            return;
        }
        // 金额校验 验证
        withdraw = new DecimalFormat("0.00").format(Double.parseDouble(withdraw));
        withdrawalInformation.setBalance(withdraw);
        if (!withdraw.matches("^[0-9]+([.]{1}[0-9]+){0,1}$")) {
            DialogUtils.showToast(context, "提现金额格式错误");
            return;
        }
        // 整数 小数只能有两位
        if (withdraw.split("\\.").length == 2 && withdraw.split("\\.")[1].length() > 2) {
            DialogUtils.showToast(context, "提现金额格式错误");
            return;
        }
        if (Double.parseDouble(withdraw) > Double.parseDouble(walletaMnagement.getBalance().toString())) {
            DialogUtils.showToast(context, "提现金额不能大于余额");
            return;
        }
        if (Double.parseDouble(withdraw) <= 0) {
            DialogUtils.showToast(context, "提现金额必须大于0");
            return;
        }
        if (Double.parseDouble(withdraw) > 10000) {
            DialogUtils.showToast(context, "提现金额不能大于10000");
            return;
        }

        DialogUtils.showConfirmDialog(context, "提现通知", "确定提现【" + withdraw + "】吗？", (dialog, which) -> {
            walletApi.performSubmitWithdrawAsync(withdrawalInformation, new BaseCallbac<JsonObject>() {
                @Override
                public void onSuccess(JsonObject data) {
                    runOnUiThread(() -> {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        if (!data.get("success").getAsBoolean()) {
                            return;
                        }
                        // 暂停一秒
                        DialogUtils.sleep(1000);

                        // 返回上一页
                        finish();
                    });
                }

                @Override
                public void onFailure(String errorMessage) {
                    runOnUiThread(() -> {
                        DialogUtils.showToast(context, errorMessage);
                    });
                }
            });
        });
    }

    class ViewHolder {
        RadioGroup radioGroup;
        RadioButton radioAlipay;
        RadioButton radioWechat;
        EditText et_account;
        EditText et_name;
        EditText et_phone;
        TextView tv_withdraw_balance;
        EditText et_withdraw;
        MaterialButton et_submit;

        public ViewHolder() {
            radioGroup = findViewById(R.id.radioGroup);
            radioAlipay = findViewById(R.id.radioAlipay);
            radioWechat = findViewById(R.id.radioWechat);
            et_account = findViewById(R.id.et_account);
            et_name = findViewById(R.id.et_name);
            et_phone = findViewById(R.id.et_phone);
            tv_withdraw_balance = findViewById(R.id.tv_withdraw_balance);
            et_withdraw = findViewById(R.id.et_withdraw);
            et_submit = findViewById(R.id.et_submit);
        }
    }


}
